<!--  -->
<template>
  <a-modal
    title="字段信息"
    :visible="visible"
    :width="650"
    @ok="handleOk"
    @cancel="visible = false"
    :maskClosable="false"
    :afterClose="handleAfterClose"
  >
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item v-if="form.dataType" label="字段名称" prop="name">
        <a-input :value="form.name" :disabled="true"></a-input>
      </a-form-model-item>
      <a-form-model-item label="对外展示名称" prop="showName">
        <a-input v-model="form.showName" placeholder="请输入字段标题"></a-input>
      </a-form-model-item>
      <a-form-model-item v-if="!hidePlaceholderTypeList.includes(form.itemType)" label="默认提示">
        <!-- <a-input v-model="form.value" placeholder="引导用户在输入框中填写正确信息，例如请输入姓名等"></a-input> -->
        <a-textarea v-model="form.value" placeholder="引导用户在输入框中填写正确信息，例如请输入姓名等" :rows="3" />
      </a-form-model-item>
      <a-form-model-item label="字段类型" prop="itemTypeId">
        <a-select
          default-value="lucy"
          v-model="form.itemTypeId"
          :disabled="fixedInitField || fixedField"
          @change="handleChangeType"
        >
          <a-select-option
            v-for="option in typeList"
            :value="option.id"
            :key="option.id"
            :disabled="option.enabled === 0"
          >
            {{ option.name }}
          </a-select-option>
        </a-select>

        <template
          v-if="
            (form.itemType === 'Select' || form.itemType === 'RadioGroup' || form.itemType === 'CheckboxGroup') &&
              form.isInternalInterface !== 2
          "
        >
          <div
            v-for="(item, index) in form.customFormItemAnswerDtoList"
            :key="index"
            style="display: flex; align-items: center; margin-top: 10px"
          >
            <a-input
              v-model="item.words"
              placeholder="选项内容"
              :disabled="fixedInitField || fixedField"
              style="width: 250px"
            >
            </a-input>
            <a-icon v-if="index !== 0" type="delete" style="margin-left: 10px" @click="handleDel(index)" />
            <a-icon v-if="index === 0" type="plus-circle" style="margin-left: 10px" @click="handleAdd" />
          </div>
        </template>
      </a-form-model-item>
      <a-form-model-item v-if="form.itemType === 'Attachment'" label="默认值" prop="itemDefault">
        <UploadFileMultiple :defaultFileList="itemDefault" :maxNum="1" @uploadSuccess="uploadFileMultipleSuccess" />
      </a-form-model-item>
      <a-form-model-item
        v-else-if="form.itemType === 'AreaStreetPicker'"
        label=""
        :wrapperCol="{ span: 20, pull: 2, push: 2 }"
      >
        <TownshipSelector
          :area="defaultFormItem.content"
          :enableValue="defaultFormItem.enableValue"
          @getArea="handleGetArea"
        />
      </a-form-model-item>
      <a-form-model-item v-else-if="showDefaultValueItem" label="默认值">
        <FormItem ref="defaultFormItem" :formItem="defaultFormItem" />
        <!-- form.itemDefault -->
      </a-form-model-item>
      <a-form-model-item label="是否必填">
        <a-switch v-model="form.isRequired" :disabled="fixedInitField || form.itemType === 'Attachment'" />
        <!-- <a-radio-group v-model="form.isRequired">
          <a-radio :value="1"> 是 </a-radio>
          <a-radio v-if="!fixedInitField" :value="0"> 否 </a-radio>
        </a-radio-group> -->
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { customFormItemTypeList } from '@/api/member/member'
import UploadFileMultiple from '@/components/UploadFile/multiple.vue'
import { convertFieldValue } from '@/api/member/member'
import { cloneDeep, isObject, isArray } from 'lodash-es'
import FormItem from '@/components/FormItem'
import TownshipSelector from '@/components/TownshipSelector/index.vue'

//isInternalInterface 0: 普通数据，1、接口数据，2、字典数据，3、搜索数据

const initForm = {
  id: undefined,
  formGroupId: undefined,
  formStageId: undefined,
  customFromId: undefined,
  name: undefined,
  enableValue: 2,
  isRequired: true,
  itemTypeId: 1,
  itemType: 'Input',
  optionType: 1,
  customFormItemAnswerDtoList: [],
  value: undefined,
  showName: undefined,
  isAllowWrite: 1,
  isInternalInterface: 0,
  sort: 1,
  fieldLibraryId: undefined,
  moduleType: undefined,
  type: undefined,
  dataType: undefined,
  length: undefined,
  itemDefault: []
}

const defaultFormItem = {}

export default {
  components: {
    UploadFileMultiple,
    TownshipSelector,
    FormItem
  },
  data() {
    return {
      visible: false,
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      form: cloneDeep(initForm),
      defaultFormItem: cloneDeep(defaultFormItem),
      rules: {
        name: [{ required: true, message: '请输入字段名称', trigger: 'change' }],
        itemTypeId: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
        itemDefault: [
          {
            required: true,
            type: 'array',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!value || !value.length) {
                callback('请选择默认值')
                return
              }
              callback()
            }
          }
        ],
        showName: [{ required: true, message: '请输入对外显示名称', trigger: 'blur' }]
      },
      type: 'add',
      typeList: [],
      hidePlaceholderTypeList: ['RadioGroup', 'CheckboxGroup', 'Switch'],
      itemDefault: []
    }
  },
  computed: {
    showDefaultValueItem() {
      return this.form.dataType && this.form.itemType === 'Select'
    },
    fixedInitField() {
      return this.form.isAllowWrite === 0
    },
    fixedField() {
      return this.form.fieldLibraryId > 0
    }
  },
  watch: {
    'form.itemType'(val) {
      if (val === 'Select' || val === 'RadioGroup' || val === 'CheckboxGroup') {
        let { id, formGroupId, formStageId, customFromId, moduleType, isInternalInterface } = this.form
        if (this.form.customFormItemAnswerDtoList && this.form.customFormItemAnswerDtoList.length) return
        if (isInternalInterface === 0) {
          this.form.customFormItemAnswerDtoList = [
            {
              customFormItemId: id,
              formGroupId,
              moduleType,
              formStageId,
              customFromId,
              // optionsName: undefined,
              words: undefined
            }
          ]
        }
      }
    }
  },
  methods: {
    handleAfterClose() {
      this.form = cloneDeep(initForm)
      this.defaultFormItem = cloneDeep(defaultFormItem)
    },
    show(obj) {
      this.type = obj.type
      Object.keys(this.form).forEach(k => {
        this.form[k] = this.type === 'edit' ? obj.data[k] : undefined
      })
      if (obj.type === 'add') {
        this.form.isAllowWrite = 1
        this.form.moduleType = obj.data.moduleType
        this.form.isInternalInterface = 0
      }

      const value = convertFieldValue({ content: '' }, obj.data)
      this.form.itemDefault = value
      this.itemDefault = value

      if (this.form.itemType === 'Attachment') {
        this.form.isRequired = false
      } else {
        this.form.isRequired = obj.data.isRequired === 1
      }
      this.form.optionType =
        obj.data.customFormItemAnswerDtoList && obj.data.customFormItemAnswerDtoList.length ? 1 : undefined

      this.visible = true
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate()
      })

      this.defaultFormItem = {
        ...this.form,
        showName: '',
        value: '请选择默认值',
        content: this.itemDefaultProcess()
      }
    },
    async getCustomFormItemTypeList() {
      let res = await customFormItemTypeList()
      this.typeList = res.data || []
    },
    handleDel(index) {
      if (this.fixedInitField || this.fixedField) return
      this.form.customFormItemAnswerDtoList.splice(index, 1)
    },
    handleAdd() {
      if (this.fixedInitField || this.fixedField) return
      let { id, formGroupId, formStageId, customFromId, moduleType } = this.form
      this.form.customFormItemAnswerDtoList.push({
        customFormItemId: id,
        formGroupId,
        moduleType,
        formStageId,
        customFromId,
        // optionsName: undefined,
        words: undefined
      })
    },
    //类型选择回调
    handleChangeType(val) {
      let item = this.typeList.find(f => f.id === val)
      this.form.itemType = item.type
      this.form.itemDefault = []
      if (item.type === 'Attachment') {
        this.form.isRequired = false
      }
    },
    itemDefaultProcess() {
      if (this.form.itemType === 'AreaStreetPicker') {
        if (isArray(this.form.itemDefault)) return this.form.itemDefault.map(v => Number(v))
        if (this.form.itemDefault) return [this.form.itemDefault]
        return []
      } else {
        return this.form.itemDefault
      }
    },
    handleGetArea({ area, enableValue }) {
      this.defaultFormItem.content = area
      this.defaultFormItem.enableValue = enableValue
    },
    handleOk() {
      const that = this

      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const formData = cloneDeep(this.form)

          if (this.form.itemType === 'AreaStreetPicker') {
            formData.itemDefault = this.defaultFormItem.content
            formData.enableValue = this.defaultFormItem.enableValue || 1
          }
          if (formData.itemType === 'Attachment' && isObject(formData.itemDefault[0])) {
            formData.itemDefault[0] = JSON.stringify(formData.itemDefault[0])
          }
          if (
            formData.isInternalInterface === 0 &&
            (formData.itemType === 'Select' ||
              formData.itemType === 'RadioGroup' ||
              formData.itemType === 'CheckboxGroup')
          ) {
            if (
              !formData.customFormItemAnswerDtoList ||
              formData.customFormItemAnswerDtoList.filter(f => !f.words).length
            ) {
              return this.$message.error('请补充选项')
            }
          }

          if (that.showDefaultValueItem) {
            // 存在默认值
            const { content } = that.$refs.defaultFormItem.formItem
            formData.itemDefault = isArray(content) ? content : [content]
          }

          if (this.type === 'add') {
            this.$emit('addField', {
              ...formData,
              isRequired: formData.isRequired ? 1 : 0,
              name: formData.dataType ? formData.name : '自定义'
            })
          } else {
            this.$emit('editField', {
              ...formData,
              isRequired: formData.isRequired ? 1 : 0,
              name: formData.dataType ? formData.name : '自定义'
            })
          }
          this.visible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    uploadFileMultipleSuccess(fileList) {
      if (fileList.length) {
        this.$refs.ruleForm.clearValidate('itemDefault')
      }
      this.form.itemDefault = fileList.length ? [JSON.stringify(fileList[0])] : []
    }
  },
  created() {
    this.getCustomFormItemTypeList()
  },
  mounted() {}
}
</script>
<style scoped></style>
